<!--
  * 硬件接口表单
-->
<template>
  <a-modal :title="formData.id ? '修改' : '新增'" :width="1000" :open="visibleFlag" @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical" :disabled="props.formType == 'view'">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="设备厂商" name="manufacturerId">
            <CustomSelect
              v-model:value="formData.manufacturerId"
              :placeholder="'请选择设备厂商'"
              queryParamKey="manufacturerName"
              :api="manufacturerApi.page"
              @change="(...data) => handleChange(data)"
              label-field="manufacturerName,id"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label=" 设备类型" name="deviceType">
            <a-select v-model:value="formData.deviceType" allowClear :options="DEVICE_TYPE" placeholder="请选择设备类型" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="备注" name="remark">
            <a-textarea v-model:value="formData.remark" placeholder="请输入备注" />
          </a-form-item>
        </a-col>
      </a-row>
      <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">硬件应用信息</group-title>
      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label=" 应用信息" name="content">
            <a-textarea v-model:value="formData.content" placeholder='请输入json字符串,如：{"aaa": 111}' />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div v-if="props.formType == 'view'">
      <DeviceModuleList :row-data="props.rowData" class="m-b-4" formType="view" />
      <DeviceModuleList v-if="props.rowData.deviceType == '1'" :type="1" :row-data="props.rowData" formType="view" />
    </div>

    <template #footer>
      <a-space v-if="props.formType != 'view'">
        <a-button @click="onReset" type="link">重置</a-button>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template></a-modal
  >
</template>
<script setup>
  import { reactive, ref, nextTick, computed, watch } from 'vue'
  import _ from 'lodash'
  import { message } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { smartSentry } from '/@/lib/smart-sentry'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { strToArr } from '/@/utils/common'
  import { manufacturerApi } from '/@/api/business/b-operation/manufacturer/index'
  import { deviceModuleApi } from '/@/api/business/b-operation/device-module/index'
  import { validateJSON } from '/@/utils/validate'
  import { DEVICE_TYPE } from '/@/constants/dict'
  import DeviceModuleList from './device-module-list.vue'

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['ok', 'update:open'])
  const visibleFlag = computed({ get: () => props.open, set: (val) => emits('update:open', val) })

  function onReset() {
    Object.assign(formData.value, formDefault)
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
  // ------------------------ 显示与隐藏 ------------------------
  function onClose() {
    Object.assign(formData.value, formDefault)
    visibleFlag.value = false
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }

  // ------------------------ 获取表单数据 ------------------------
  async function getFormData(data) {
    SmartLoading.show()
    try {
      let res = await deviceModuleApi.findId(data)
      formData.value = { ...res.data }
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }
  /* 切换厂商 */
  function handleChange(data) {
    console.log(data)

    if (!data?.[1][0]) {
      formData.value.manufacturerName = undefined
      return
    }
    formData.value.manufacturerName = data[1][0].manufacturerName
  }
  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref()

  const formDefault = {
    deviceType: undefined, //设备类型 0云喇叭 1云打印
    manufacturerName: undefined, //厂商名称
    manufacturerId: undefined, //厂商编号
    serverName: undefined, //应用名称
    content: undefined, //应用信息
    cTime: undefined, //创建时间
    deviceCode: undefined, //产品型号
    cUserId: undefined, //创建用户编号
    uUserId: undefined, //更新用户编号
    cUserName: undefined, //创建人
    uUserName: undefined, //更新人
    uTime: undefined, //更新时间
    id: undefined, //编号
    status: undefined, //状态是否启用 0 否 1是
  }

  let formData = ref({ ...formDefault })

  const rules = {
    manufacturerId: [{ required: true, message: '设备厂商 必填' }],
    deviceType: [{ required: true, message: '设备类型 必填' }],
    content: [
      { required: true, message: '应用信息 必填' },
      {
        validator: validateJSON,
      },
    ],
  }

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields()
      save()
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!')
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show()
    try {
      let data = { ...formData.value }
      if (formData.value.id) {
        await deviceModuleApi.update(data)
      } else {
        await deviceModuleApi.insert(data)
      }
      message.success('操作成功')
      emits('ok')
      onClose()
    } catch (err) {
      smartSentry.captureError(err)
    } finally {
      SmartLoading.hide()
    }
  }

  const deviceCodeOptions = ref([])

  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      console.log('formData.value==>', formData.value)

      if (props.open && props.rowData && props.formType != 'add') {
        getFormData(val[0])
      }
    },
    { immediate: true },
  )
</script>
